package com.aaa.utils;

import com.aaa.mq.ActivityMqConfig;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

@Component
public class ActivityUtil {

    @Resource
    RabbitTemplate rabbitTemplate;

    public void sendMsg(String exchange, String key, Object message, Date date) {
        rabbitTemplate.convertAndSend(exchange, key, message, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                MessageProperties messageProperties = message.getMessageProperties();
                // 设置消息过期时间：进入死信队列，设置活动开始，当前时间-活动时间
                Long l = Math.abs(Duration.between(LocalDateTime.now(), date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime()).toMillis());
                messageProperties.setExpiration(l.toString());// 毫秒
                return message;
            }
        });
    }

}
